import type { DomainModel } from '@/apis/model/domain'
import ToastUtils from '@/utils/toast'

/**
 * 域名操作相关函数，不要涉及状态
 * @param refreshFn 列表刷新函数，用于一些操作完成后刷新列表
 * @returns
 */
export default function useDomainActions(refreshFn: PromiseFn) {
  const router = useRouter()

  const { setMessageBox } = useMessageBox()

  /**
   * 删除
   */
  const handleDelete = (row: DomainModel) => {
    setMessageBox({
      isHtml: true,
      content:
        '<p>确定删除此域名？</p><p>删除域名，解析记录会同步删除，且无法恢复。</p>',
      title: '删除域名提示',
      async submit() {
        try {
          await deleteDomainApi({ id: row.id! })
          refreshFn()
          ToastUtils.success('删除成功')

          setMessageBox({ visible: false })
        } finally {
          setMessageBox({ loading: false })
        }
      }
    })
  }

  /**
   * 修改dns地址
   */
  const handleEditDnsServer = async (id: string, dns: [string, string]) => {
    await editDomainDnsApi({
      id,
      ns_id_list: dns
    })
  }

  /**
   * 修改备注
   */
  const handleEditRemark = async (row: DomainModel, remark: string) => {
    await editDomainApi({ id: row.id!, remark })
    refreshFn()
    ToastUtils.success('修改成功')
  }

  /**
   * 调整指定域名解析页面
   */
  const toParseSetting = (row: DomainModel) => {
    router.push({
      name: 'DomainParseSetting',
      params: { id: row.id },
      query: { name: row.name }
    })
  }

  return {
    handleDelete,
    handleEditDnsServer,
    handleEditRemark,
    toParseSetting
  }
}
